<!-- 编辑查看弹框 -->
<template>
  <el-dialog
    width="50%"
    :append-to-body="false"
    :modal-append-to-body="true"
    :modal="true"
    :close-on-click-modal="false"
    :lock-scroll="true"
    class="pms-dialog"
    :visible.sync="isShowCheck"
    :before-close="close"
    top="25vh"
  >
    <template slot="title">
      <div class="title-reset">{{ getTableInfo.materialName }}</div>
    </template>
    <!-- 物资绑定信息表格-->
    <div :class="[+isType === 0 ? 'materia-table' : 'materia-table-cancel']">
      <OrderTable
        id="id"
        ref="myTableRef"
        :is-mar-class="true"
        :table-data="getMateriaCheckBindTable"
        :columns="checkOptions.columns"
        :url-data="urlData"
        :is-sub-check-eidt="true"
        @rowClick="rowClick"
        @inputChange="hanldeinputChange"
      />
    </div>
    <!--展示表格剩余信息 -->
    <div class="show-tableinfo">
      <li v-for="(item, _, index) in getTableInfo" :key="index">
        <span class="title"><span>{{ getTitle(index) }}</span> {{ item
        }}</span>
      </li>
    </div>
    <!-- 自定义按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button v-if="!Number(isType)" class="pms-button-primary" size="small" @click="save()">保存</el-button>
      <el-button class="pms-button-primary" size="small" @click="close()">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { colOptionCheckBind, colOptionEditBind } from '../index.js'
import OrderTable from '../components/OrderTable.vue'
import {
    saveProductBinding,
    getSubProductList
} from '@/api/settlement/balanceSettlement.js'
import { Message } from 'element-ui'
export default {
    name: 'CheckEditPop',
    components: {
        OrderTable
    },
    props: {
        // 是否打开弹框
        isShowCheck: {
            type: Boolean,
            default: false
        },
        // 编辑0 查看1
        isType: {
            type: String,
            default: '0'
        },
        // 查看当前行的数据
        saveTempRow: {
            type: Object,
            default: () => ({ })
        },
        // 浏览器携带参数
        urlData: {
            type: Object,
            default: () => ({ })
        }
    },
    data() {
        return {
            // 表格配置项
            checkOptions: {
                // 查看表头
                colOptionCheckBind,
                // 编辑表头
                colOptionEditBind,
                // 表头
                columns: [],
                // 表格数据
                materiaCheckBindTable: [
                ]
            },
            provisionalCount: '', // 暂存当前编辑单元格的值
            deepTable: {}, // 深拷贝一份表格数据保存的时候需要判断是否编辑了
            recordIndex: []// 是否编辑单元格存储
        }
    },
    computed: {
        // 表格数据
        getMateriaCheckBindTable() {
            return this.checkOptions.materiaCheckBindTable
        },
        // 获取展示行信息
        getTableInfo() {
            // 让那几个字段展示
            const requireType = ['materialCode', 'materialName', 'amount', 'currentAmount']
            const show = this.getMateriaCheckBindTable !== undefined && this.getMateriaCheckBindTable.length > 0
            return show ? this.extractProperties(this.deepTable, requireType) : {}
        }
    },
    watch: {
        // 判断当前是查看 还是编辑进来的
        isType: {
            handler(newVal) {
                // 0 编辑 1查看
                this.checkOptions.columns = newVal === '0' ? colOptionEditBind : colOptionCheckBind
                this.initSubMajorTable()
            },
            deep: true,
            immediate: true
        },
        saveTempRow: {
            handler(newVal) {
                this.initSubMajorTable()
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        // 遍历一个对象返回需要的对象 tyoe []
        extractProperties(obj, typeArr) {
            // 计算的结果值
            const numResult = this.accumulate(this.getMateriaCheckBindTable)
            obj.currentAmount = numResult
            return typeArr.reduce((result, key) => {
                if (key in obj) {
                    result[key] = obj[key]
                }
                return result
            }, {})
        },
        // 获取title
        getTitle(index) {
            return index === 2 ? '可绑定总数:' : index === 3 ? '本次绑定数量之和:' : ''
        },
        accumulate(arr) {
            let sum = 0
            for (let i = 0; i < arr.length; i++) {
                if (!isNaN(arr[i].currentAmount)) {
                    sum += Number(arr[i].currentAmount)
                }
            }
            return sum
        },
        // 处理保存后需要传的数据格式
        transformObject(data) {
            const { bundingId } = this.saveTempRow
            // 改为需要的字段
            const result = data.map(item => {
                return {
                    otherAttrCode: item.otherAttrCode,
                    currentAmount: item.currentAmount
                }
            })
            const newObj = {
                bundingId: bundingId,
                productSubSpecInfo: result
            }
            return newObj
        },
        // 保存
        async save() {
            // 如果没有改变则不允许保存
            if (this.recordIndex.length === 0) {
                return this.$message({
                    message: '没有任何修改，请关闭页面或修改本次绑定数量后再保存"'
                })
            }
            // 子专业绑定 的数量
            const result = this.accumulate(this.getMateriaCheckBindTable)
            if (+this.getTableInfo?.amount !== +result) {
                this.messagePrompt('本次可绑定数量之和必须与可绑定总数相等！')
            } else {
                this.secondaryConfirmSave()
            }
        },
        // 二次确认保存子项目
        async secondaryConfirmSave() {
            this.$confirm('点击保存后，在下次退审前将不允许修改建设子专业绑定信息,请确认是否需要保存！', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            }).then(async() => {
                const res = await saveProductBinding(this.transformObject(this.getMateriaCheckBindTable))
                if (+res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '保存成功!'
                    })
                    this.close()
                }
            }).catch(() => {
                this.getMateriaCheckBindTable.forEach(item => {
                    item.currentAmount = 0
                })
            })
        },
        // 关闭弹框
        close() {
            this.$emit('closeDialog', false)
        },
        // 点击行事件
        rowClick(row) {
            // 暂存某个单元格的值
            const [, , lastCount] = row
            this.provisionalCount = lastCount
        },
        // 修改单元的数据
        hanldeinputChange(data) {
            // 保存当前是否编辑单元格
            this.recordIndex.push(data[1])
        },
        // 获取表格初始化数据
        async initSubMajorTable() {
            const { bundingId, categoryCode } = this.saveTempRow
            if (bundingId !== undefined && categoryCode !== undefined) {
                const { code, data } = await getSubProductList(bundingId, categoryCode)
                if (+code === 200) {
                    this.checkOptions.materiaCheckBindTable = data
                    // 深拷贝一份数据 保存的时候需要判断
                    this.deepTable = JSON.parse(JSON.stringify(this.checkOptions.materiaCheckBindTable[0]))
                }
            }
        },
        messagePrompt(message) {
            Message({
                message: message,
                type: 'warning'
            })
        },
        // 判断数组对象的每一项是否相等 递归遍历
        deepEqual(a, b) {
            // 判断如果相等则返回true
            if (a === b) {
                return true
            }
            // 判断是否==null 是否是对象 如果是 则返回false
            if (a == null || typeof a !== 'object' || b == null || typeof b !== 'object') {
                return false
            }
            // 遍历对象中的每一项
            const keysA = Object.keys(a)
            const keysB = Object.keys(b)
            // 判断keysA 的长度如果不==keysB 则返回false
            if (keysA.length !== keysB.length) {
                return false
            }
            // for循环遍历每一项 获得每一项之后去判断如果！true 则返回false
            for (let i = 0; i < keysA.length; i++) {
                const key = keysA[i]
                if (!this.deepEqual(a[key], b[key])) {
                    return false
                }
            }
            // 最终返回的值
            return true
        }
    }
}

</script>
<style lang="scss" scoped>
::v-deep .el-dialog .el-dialog__header {
    text-align: left !important;
}

.show-tableinfo {
    width: 100%;
    border: 1px solid #ebeef5;
    padding-top: 9px;
    display: flex;
    justify-content: center;
    padding-left: 40px;

    li {
        list-style: none;
        width: 166px;
        height: 100%;
        margin-right: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 70px;
    }

    li:nth-child(2) {
        width: 240px;
        .title {
            color: #02A7F0;
        }
    }

    li:nth-child(3) {
        width: 120px;
    }

    li:nth-child(4) {
        width: 200px;
    }

    li:nth-child(4) .title {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    li .title {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        word-wrap: break-word;
        overflow-wrap: break-word;
        display: block;
        color: #606266;
        font-size: 12px !important;
        line-height: 1.5;
        text-align: center;
    }
}

.title-reset {
    width: 95%;
    height: 38px;
    line-height: 38px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

::v-deep .el-table__row td:nth-child(3) .cell .header-tooltip {
    margin-left: 8px;
    width: 130px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}

::v-deep .materia-table .myTable .el-table__body-wrapper .el-table__body .el-table__row td:last-child {
    background: #fffaee;
}

::v-deep .materia-table-cancel .myTable .el-table__body-wrapper .el-table__body .el-table__row td:last-child {
    background: '';
}
</style>
